package com.yumeng.framework.auth.shiro;

import com.yumeng.common.auth.AbsAuthHelper;
import com.yumeng.common.auth.BaseAuthInfo;
import com.yumeng.framework.auth.bean.authinfo.AnonAuthInfo;
import com.yumeng.framework.auth.bean.authinfo.UnknownAuthInfo;
import com.yumeng.framework.auth.exception.ShiroAuthException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.util.ThreadContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

/**
 *
 * @author wxd
 * @date 2025/9/22 14:58
 */
@Slf4j
@Component
public class ShiroAuthHelper extends AbsAuthHelper {

    //jwt模式下，每次访问在filter中都需调用subject.login(token)，此处才能获取到认证对象
    @Override
    protected BaseAuthInfo doGetCurrAuthInfo(boolean strict) {
        if (ThreadContext.getSecurityManager() != null){//为解决定时任务中 调用ShiroUtils.getCurrAuthInfo()时报错
            Object principal = SecurityUtils.getSubject().getPrincipal();
            if (principal != null){
                return  (BaseAuthInfo)principal;
            }
        }else {
            return UnknownAuthInfo.getSingleInstance();
        }
        if (strict){
            throw new ShiroAuthException("当前认证信息未知");
        }else{
            return AnonAuthInfo.getSingleInstance();
        }
    }

    @Override
    protected void printAuthFrameInfo(ConfigurableApplicationContext context) {
        log.warn("ShiroAuthHelper :: printAuthFrameInfo 待实现");
    }

    @Override
    protected boolean needThrowException(Exception ex) {
        return false;
    }

}
